package cn.ncist.health_backend.handler;

import cn.hutool.json.JSONUtil;
import cn.ncist.common.RespResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
//    Result result=new Result(false,"登录失败");
        RespResult respResult = new RespResult(false,"登录失败");
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        log.info(exception.getMessage());
        //定义一个 输出流
        ServletOutputStream outputStream = response.getOutputStream();
        if (exception.getMessage().equals("验证码错误")){
            respResult.setMessage("验证码错误");
        }else {
            respResult.setMessage("用户名或者密码错误");
        }

        outputStream.write(JSONUtil.toJsonStr(respResult).getBytes("UTF-8"));
        //
        outputStream.flush();
        outputStream.close();
    }
}
